<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    design
 * @package     default_default
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */
?>
<?php
    // Construct unique ID
    $_htmlId = $this->getHtmlId() ? $this->getHtmlId():'_'.uniqid();

    // Determine column span
    $_colspan = 2;
    if (!$this->_addAfter) {
        $_colspan -= 1;
    }
    $_colspan = $_colspan > 1 ? 'colspan="'.$_colspan.'"':'';
?>

<div class="grid" id="grid<?php echo $_htmlId ?>">
    <table cellpadding="0" cellspacing="0" class="border">
        <tbody>
            <tr class="headings" id="headings<?php echo $_htmlId ?>">
                <?php foreach ($this->_columns as $columnName => $column): ?>
                    <th><?php echo $column['label'] ?></th>
                <?php endforeach;?>
                <th <?php echo $_colspan ?>></th>
            </tr>
            <tr id="addRow<?php echo $_htmlId ?>">
                <td colspan="<?php echo count($this->_columns) ?>"></td>
                <td <?php echo $_colspan?>>
                    <button style="" onclick="" class="scalable add" type="button" id="addToEndBtn<?php echo $_htmlId ?>">
                        <span><?php echo $this->_addButtonLabel ?></span>
                    </button>
                </td>
            </tr>
        </tbody>
    </table>
    <input type="hidden" name="<?php echo $this->getElement()->getName() ?>[__empty]" value="" />
</div>

<div id="empty<?php echo $_htmlId ?>">
    <button style="" onclick="" class="scalable add" type="button" id="emptyAddBtn<?php echo $_htmlId ?>">
        <span><?php echo $this->_addButtonLabel ?></span>
    </button>
</div>

<script type="text/javascript">
//<![CDATA[
// create row creator
var arrayRow = {
    // define row prototypeJS template
    template: new Template(
        '<tr id="#{_id}">'
            <?php foreach ($this->_columns as $columnName => $column): ?>
                + '<td class="#{_id}-<?php echo $columnName?>">' + '<?php echo Mage::helper('core')->jsQuoteEscape($this->_renderCellTemplate($columnName))?>' + '</td>'
            <?php endforeach;?>
            <?php if ($this->_addAfter): ?>
                + '<td><button onclick="" class="scalable add" type="button" id="addAfterBtn#{_id}"><span><?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('merchandiser')->__('Add after')) ?></span></button></td>'
            <?php endif; ?>
            + '<td><button test="yes" onclick="arrayRow.del(\'#{_id}\')" class="scalable delete" type="button"><span><?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('merchandiser')->__('Delete')) ?></span></button></td>'
        + '</tr>'
    ),

    rowsCount: 0,

    add: function(templateData, insertAfterId) {
        // generate default template data
        if ('' == templateData) {
            var d = new Date();
            var templateData = {
                <?php foreach ($this->_columns as $columnName => $column): ?>
                <?php echo $columnName ?> : '',
                <?php endforeach; ?>
                _id : '_' + d.getTime() + '_' + d.getMilliseconds()
            };
        }

        // insert before last row
        if ('' == insertAfterId) {
            new Insertion.Before(
                $('addRow<?php echo $_htmlId ?>'),
                this.template.evaluate(templateData)
            );
        } else {
            new Insertion.After(
                $(insertAfterId),
                this.template.evaluate(templateData)
            );
        }

        // set the selected drop-down list item
        <?php foreach ($this->_columns as $columnName => $column):?>
            var options = $$('td.' + templateData._id + '-' + '<?php echo $columnName ?>' + ' option')
            for(var index = 0; index < options.length; ++index) {
                var option = options[index]
                if(option.getAttribute('value') == templateData.<?php echo $columnName ?>) {
                    option.selected = true
                }
            }
        <?php endforeach;?>

        <?php if ($this->_addAfter): ?>
            Event.observe('addAfterBtn' + templateData._id, 'click', this.add.bind(this, '', templateData._id));
        <?php endif;?>

        this.rowsCount += 1;
        hideLastLogicSelectBox();
    },

    del: function(rowId) {
        $(rowId).remove();
        this.rowsCount -= 1;
        if (0 == this.rowsCount) {
            this.showButtonOnly();
        }
        hideLastLogicSelectBox();
    },

    showButtonOnly: function() {
        $('grid<?php echo $_htmlId ?>').hide();
        $('empty<?php echo $_htmlId ?>').show();
    }
}

// bind add action to "Add" button in last row
Event.observe('addToEndBtn<?php echo $_htmlId ?>', 'click', arrayRow.add.bind(arrayRow, '', ''));

// add existing rows
<?php
$_addAfterId = "headings{$_htmlId}";
foreach ($this->getArrayRows() as $_rowId => $_row) {
    echo "arrayRow.add(" . $_row->toJson() . ", '{$_addAfterId}');\n";
    $_addAfterId = $_rowId;
}
?>

// initialize standalone button
$('empty<?php echo $_htmlId ?>').hide();
Event.observe('emptyAddBtn<?php echo $_htmlId ?>', 'click', function() {
    $('grid<?php echo $_htmlId ?>').show();
    $('empty<?php echo $_htmlId ?>').hide();
    arrayRow.add('', '');
});

// if no rows, hide grid and show button only
<?php if (!$this->getArrayRows()): ?>
    arrayRow.showButtonOnly();
<?php endif; ?>

// toggle the grid, if element is disabled (depending on scope)
<?php if ($this->getElement()->getDisabled()): ?>
    toggleValueElements({checked:true}, $('grid<?php echo $_htmlId ?>').parentNode);
<?php endif; ?>

function hideLastLogicSelectBox() {
    $$('select.logic_link').each(function(item,index) {
        if(index == $$('select.logic_link').length - 1) {
            item.hide();
        } else {
            item.show();
        }
    });
}
//]]>
</script>
